package org.jeecg.modules.system.task;

import java.math.BigDecimal;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.constant.DictCode;
import org.jeecg.common.constant.enums.SysLogConfig;
import org.jeecg.common.constant.enums.SysLogOperateType;
import org.jeecg.common.constant.enums.SysLogType;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.common.util.SystemUtil;
import org.jeecg.modules.system.mapper.SysDictMapper;
import org.jeecg.modules.system.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@ConditionalOnProperty(prefix="mesh",name = "task.dbcapacity",havingValue = "true",matchIfMissing = true)
public class DBCapacityTask {

	@Autowired
	EmailUtil emailUtil;

	@Scheduled(fixedDelay = 1000 * 60)
	public void work() {
		log.info("[DBCapacity] 数据库容量检测定时器开始");
		try {
			String res = SystemUtil.run(new String[] { "du", "-s", "/mesh-controller/db/data/" });

			if (StringUtils.isNotBlank(res)) {
				String[] s = res.split("\\s+");
				if (s != null && s.length > 0 && StringUtils.isNotBlank(s[0])) {
					Long size = Long.parseLong(s[0]); // 单位：KB
					if (size != null && size > 0) {
						SysDictMapper sysDictMapper = SpringContextUtils.getBean(SysDictMapper.class);
						// 数据库容量大小
						String capacity = sysDictMapper.queryDictValueByText(DictCode.LOG_CONFIG.getCode(), SysLogConfig.CAPACITY.getName());
						if (StringUtils.isNotBlank(capacity)) {
							Integer capacitySize = Integer.parseInt(capacity); // 告警值，单位：GB
							Double currentSize = size / 1024 / 1024.0; // 实际值，单位：GB

							BigDecimal b = new BigDecimal(currentSize);
							double currentSizeDouble2 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

							log.info("[DBCapacity] 数据库容量检测结果：" + currentSizeDouble2 + "GB   告警值：" + capacitySize + "GB");

							if (currentSize >= (capacitySize * 0.9)) { // 当前值大于告警值，发日志
								log.info("[DBCapacity] 触发数据库容量告警（90%）");
								// 发送日志
								ISysBaseAPI sysBaseAPI = (ISysBaseAPI) SpringContextUtils.getBean("sysBaseAPI");
								String content = "当前容量" +currentSizeDouble2+ "GB，已超过设置的安全值"+capacitySize+"GB的90%";
								sysBaseAPI.addLog("日志容量告警", SysLogType.ALARM, SysLogOperateType.CAPACITY, null, content, "日志容量");
								log.info("[DBCapacity] 数据库容量发送日志成功");

								// 发送邮件
								emailUtil.sendEmail("日志容量告警", content);
								log.info("[DBCapacity] 数据库容量发送邮件成功");

							}
						}
					}
				}
			}
		} catch (Exception e) {
			log.error("[DBCapacity] 数据库容量检测定时器错误", e);
		}
		log.info("[DBCapacity] 数据库容量检测定时器结束");
	}

}
